package com.hh.xx.thrift;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.*;

/**
 * @author tzp
 * @since 2020/5/13
 */
public class CalculatorClient {
    public static void main(String[] args) {

        try {
            TTransport transport = new TSocket("localhost", 9862);
            transport.open();

            TProtocol protocol = new TBinaryProtocol(transport);
            TCalculator.Client client = new TCalculator.Client(protocol);

            perform(client);

            transport.close();
        } catch (TException x) {
            x.printStackTrace();
        }
    }

    private static void perform(TCalculator.Client client) throws TException {
        client.ping();
        System.out.println("ping()");

        int sum = client.add(1, 1);
        System.out.println("1+1=" + sum);

        TWork work = new TWork();

        work.op = TOperation.DIVIDE;
        work.num1 = 1;
        work.num2 = 0;
        try {
            int quotient = client.calculate(1, work);
            System.out.println("Whoa we can divide by 0");
        } catch (TInvalidOperation io) {
            System.out.println("Invalid operation: " + io.why);
        }

        work.op = TOperation.SUBTRACT;
        work.num1 = 15;
        work.num2 = 10;
        try {
            int diff = client.calculate(1, work);
            System.out.println("15-10=" + diff);
        } catch (TInvalidOperation io) {
            System.out.println("Invalid operation: " + io.why);
        }

    }
}
